package com.hgnu.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hgnu.common.BaseContext;
import com.hgnu.common.R;
import com.hgnu.dto.OrdersDto;
import com.hgnu.pojo.OrderDetail;
import com.hgnu.pojo.Orders;
import com.hgnu.pojo.ShoppingCart;
import com.hgnu.service.OrderDetailService;
import com.hgnu.service.OrdersService;
import com.hgnu.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/order")
public class OrdersController {
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private ShoppingCartService shoppingCartService;
    //用户下单
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders){//接收addressBookId
        ordersService.submit(orders);
        return R.success("用户下单成功");
    }
    /*//用户再下一单
    @PostMapping("/again")
    public R<String> submitagain(@RequestBody Orders orders){
        Long copyId = orders.getId();//被复制的菜单表Id
        long orderId= IdWorker.getId();//订单号

        //先复制菜单表
        Orders order1 = ordersService.getById(copyId);
        BeanUtils.copyProperties(order1,orders);
        orders.setId(orderId);
        orders.setNumber(String.valueOf(orderId));
        orders.setStatus(2);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now().plusHours(1));
        ordersService.save(orders);

        //再复制菜单明细表
        LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderDetail::getOrderId,copyId);
        List<OrderDetail> listOne = orderDetailService.list(queryWrapper);
        for (OrderDetail list:listOne){
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(list,orderDetail);
            orderDetail.setOrderId(orderId);
            orderDetail.setId(IdWorker.getId());
            orderDetailService.save(orderDetail);
        }
        return R.success("用户再次下单成功");
    }*/

    /**
     * 再来一单
     * @param map
     * @return
     */
    @PostMapping("/again")
    public R<String> againSubmit(@RequestBody Map<String,String> map){
        String ids = map.get("id");

        long id = Long.parseLong(ids);

        LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderDetail::getOrderId,id);
        //获取该订单对应的所有的订单明细表
        List<OrderDetail> orderDetailList = orderDetailService.list(queryWrapper);

        //通过用户id把原来的购物车给清空，这里的clean方法就是之前的购物车清空方法
        shoppingCartService.clean();
        //获取用户id
        Long userId = BaseContext.getCurrentId();
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map((item) -> {
            //把从order表中和order_details表中获取到的数据赋值给这个购物车对象
            ShoppingCart shoppingCart = new ShoppingCart();
            shoppingCart.setUserId(userId);
            shoppingCart.setImage(item.getImage());
            Long dishId = item.getDishId();
            Long setmealId = item.getSetmealId();
            if (dishId != null) {
                //如果是菜品那就设置菜品ID
                shoppingCart.setDishId(dishId);
            } else {
                //添加到购物车的是套餐
                shoppingCart.setSetmealId(setmealId);
            }
            shoppingCart.setName(item.getName());
            shoppingCart.setDishFlavor(item.getDishFlavor());
            shoppingCart.setNumber(item.getNumber());
            shoppingCart.setAmount(item.getAmount());
            shoppingCart.setCreateTime(LocalDateTime.now());
            return shoppingCart;
        }).collect(Collectors.toList());

        //把携带数据的购物车批量插入购物车表  这个批量保存的方法要使用熟练！！！
        shoppingCartService.saveBatch(shoppingCartList);

        return R.success("操作成功");
    }

    //订单明细查询
    @GetMapping("/userPage")
    public R<Page> page(int page,int pageSize){
        Page<Orders> pageinfo = new Page<>(page,pageSize);
        Page<OrdersDto> ordersDtoPage = new Page<>();
        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getUserId,userId);
        queryWrapper.orderByDesc(Orders::getOrderTime);
        ordersService.page(pageinfo,queryWrapper);
        BeanUtils.copyProperties(pageinfo,ordersDtoPage,"records");
        List<Orders> records = pageinfo.getRecords();
        List<OrdersDto> ordersDtoslist = records.stream().map((item) -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(item, ordersDto);
            Long orderId = item.getId();
            LambdaQueryWrapper<OrderDetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(OrderDetail::getOrderId, orderId);
            List<OrderDetail> orderDetails = orderDetailService.list(lambdaQueryWrapper);
            ordersDto.setOrderDetails(orderDetails);
            return ordersDto;
        }).collect(Collectors.toList());
        ordersDtoPage.setRecords(ordersDtoslist);
        return R.success(ordersDtoPage);
    }
    //订单查询（管理端）
    @GetMapping("/page")
    public R<Page> pageUser(int page,int pageSize,Long number,String beginTime, String endTime){
        Page<Orders> pageinfo = new Page<>(page,pageSize);
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(number!= null,Orders::getId,number)
                .gt(StringUtils.isNotBlank(beginTime),Orders::getOrderTime,beginTime)
                .lt(StringUtils.isNotBlank(endTime),Orders::getOrderTime,endTime);
        ordersService.page(pageinfo,queryWrapper);
        return R.success(pageinfo);
    }
    //更改订单状态（服务端更改）
    @PutMapping
    public R<String> setStatus(@RequestBody Orders orders){
        Long id = orders.getId();
        Integer status = orders.getStatus();
        Orders orders1 = ordersService.getById(id);
        orders1.setStatus(status);
        ordersService.updateById(orders1);
        return R.success("派送成功");
    }
}
